<template>
  <div class="user hiddenScroll">
    <LayoutContainer ref="layoutRef">
      <div class="header" v-if="userInfo">
        <div class="first flex-box">
          <!-- 头像和用户名 -->
          <div class="avatar-and-main-info">
            <el-avatar :size="60" :src="circleUrl" @click="onBig" />
            <span class="name-and-des">
              <span class="name">{{ userInfo.name }}</span>
              <span class="des">
                个人简介：{{ userInfo.biography ? userInfo.biography : '保护环境，从我做起' }}
              </span>
            </span>
            <b>{{ userInfo.gender ? '♂' : '♀' }}</b>
          </div>
          <!-- 编辑资料和新增健康记录 -->
          <div class="edit-and-add">
            <el-button round @click="avatarVisible = true">修改头像</el-button>
            <el-button round @click="changeInfo">编辑资料</el-button>
            <el-button round @click="unLogin">退出登录</el-button>
            <el-popover placement="top-start" trigger="hover" content="这里可以充值余额">
              <template #reference>
                <el-button type="success" :icon="Plus" circle @click="balanceVisible = true" />
              </template>
            </el-popover>
          </div>
        </div>
        <!-- 显示信息主要部分 -->
        <div class="second-header">
          <el-descriptions :column="3">
            <el-descriptions-item label="帐号">{{ userInfo.id }}</el-descriptions-item>
            <el-descriptions-item label="email">{{ userInfo.email }}</el-descriptions-item>
            <el-descriptions-item label="联系电话">{{ userInfo.phone }}</el-descriptions-item>
            <el-descriptions-item label="生日" :span="2">
              {{ userInfo.birthday }}
            </el-descriptions-item>
            <el-descriptions-item label="居住地址">{{ userInfo.address }}</el-descriptions-item>
            <el-descriptions-item label="帐号类型">
              <el-tag type="info" size="small">碳行者</el-tag>
              <el-tag size="small" style="margin-left: 3px" v-if="userInfo.identity">
                碳行管理员
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="账户余额">
              <span class="price">￥{{ decimalPointSave(userInfo.balanceIntegral.balance) }}</span>
              <span class="integral">∫{{ userInfo.balanceIntegral.integral }}</span>
            </el-descriptions-item>
          </el-descriptions>
        </div>
      </div>
    </LayoutContainer>
    <!-- 修改信息对话框 -->
    <ChangeInfo v-if="changeVisible" :user="userInfo" @close="closeAndRefresh"></ChangeInfo>
    <!-- 修改头像对话框 -->
    <el-dialog class="change-avatar" v-model="avatarVisible" title="更新头像" width="230" draggable destroy-on-close>
      <el-upload class="avatar-uploader" action="#" :show-file-list="false" :on-change="handleAvatarSuccess"
        :before-upload="beforeAvatarUpload" :auto-upload="false" drag>
        <img v-if="tempAvatar" :src="tempAvatar" class="avatar" />
        <el-icon v-else class="avatar-uploader-icon">
          <Plus />
        </el-icon>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="avatarVisible = false">取消</el-button>
          <el-button type="primary" @click="updateNewAvatar">更新</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 充值框 -->
    <el-dialog v-model="balanceVisible" title="充值" width="450" draggable destroy-on-close>
      <el-steps style="max-width: 600px" :active="active" finish-status="success" align-center>
        <el-step title="充值余额" />
        <el-step title="充值验证" />
      </el-steps>
      <div style="margin-bottom: 40px" />
      <el-form label-width="auto" style="width: 350px" ref="form" :model="balanceIntegral">
        <!-- 充值余额 -->
        <el-form-item label="余额" v-show="active === 0">
          <el-input v-model="balanceIntegral.balance" placeholder="充值余额" maxlength="8">
            <template #prepend>￥</template>
          </el-input>
        </el-form-item>
        <!-- 充值校验 -->
        <el-form-item label="验证码" v-show="active === 1">
          <el-input v-model="verificationCode" placeholder="请输入充值验证码" style="width: 230px" />
          <el-button type="success" class="verification-code" @click="startCountdown"
            :disabled="!isCheckVerificationCode">
            {{ isCheckVerificationCode ? '发送验证码' : countdown + 's后可重新发送' }}
          </el-button>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="balanceVisible = false">取消</el-button>
          <el-button type="primary" @click="nextOrSure">{{
            active < 2 ? '下一步' : '确定'
          }}</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import LayoutContainer from '@/layout/LayoutContainer.vue'
import {
  addMoneyAndIntegral,
  getAvatar,
  getBalanceVerificationCode,
  getBaseInfo,
  updateAvatarURL,
  verifyBalanceVerificationCode,
} from '@/api/user'
import { useUserStore } from '@/stores/modules/userStore'
import ChangeInfo from '@/views/User/components/ChangeInfo.vue'
import { Plus } from '@element-plus/icons-vue'
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { startLoading, stopLoading } from '@/utils/loading'
import { decimalPointSave } from '@/utils/strutils'
import { ElNotification } from 'element-plus'

const userStore = useUserStore()

const layoutRef = ref(null)

// 路由
const router = useRouter()

// 充值余额窗口
const balanceVisible = ref(false)

// 充值窗口步骤条
const active = ref(0)

// 是否允许发送验证码
const isCheckVerificationCode = ref(true)

// 验证码
const verificationCode = ref()

// 余额
const balanceIntegral = ref({
  balance: 0,
  integral: 0,
})

// 下一步或确定
const nextOrSure = async () => {
  if (active.value < 1) {
    if (typeof +balanceIntegral.value.balance !== 'number') {
      ElNotification({
        title: '失败',
        message: '请输入数字格式',
        type: 'error',
      })
      return
    } else if (balanceIntegral.value.balance <= 0) {
      ElNotification({
        title: '失败',
        message: '充值余额必须大于0',
        type: 'error',
      })
      return
    }
    active.value += 1
  } else if (active.value < 2) {
    // 校验验证码
    const data = (await verifyBalanceVerificationCode(verificationCode.value)).data
    if (!data.success) {
      ElNotification({
        title: '失败',
        message: '验证码错误',
        type: 'error',
      })
      return
    }
    await updateBalance()
  }
}

// 充值余额
const updateBalance = async () => {
  if (balanceIntegral.value.balance < 0) {
    ElNotification({
      title: '失败',
      message: '充值金额不能为负数',
      type: 'error',
    })
    return
  }
  //开始加载
  startLoading()
  //增加金额和积分
  const res = (await addMoneyAndIntegral(balanceIntegral.value)).data
  //暂停加载
  stopLoading()
  if (res.success) {
    balanceVisible.value = false
    await getUserInfo()
    balanceIntegral.value = { balance: 0, integral: 0 }
    ElNotification({
      title: '成功',
      message: '充值成功',
      type: 'success',
    })
    active.value = 0
  } else {
    ElNotification({
      title: '失败',
      message: '充值失败',
      type: 'error',
    })
  }
}

//六十秒倒计时
const countdown = ref(60)

//时间控制器
let timer = null

//开始倒数
const startCountdown = async () => {
  // 禁止反复点击
  isCheckVerificationCode.value = false
  // 发送验证码
  await getBalanceVerificationCode(balanceIntegral.value.balance)
  // 定义时间对象
  timer = setInterval(() => {
    if (countdown.value > 0) {
      countdown.value--
    } else {
      // 重置倒计时
      countdown.value = 60
      // 允许重新发送
      isCheckVerificationCode.value = true
      //清除时间对象
      clearInterval(timer)
    }
  }, 1000)
}

// 用户信息
const userInfo = ref()

// 获取用户信息
const getUserInfo = async () => {
  const res = (await getBaseInfo()).data

  userStore.setUser(res.data.id)
  userInfo.value = res.data
  await updateAvatar()
}

// 修改信息显示框
const changeVisible = ref(false)

// 修改信息
const changeInfo = () => {
  changeVisible.value = true
  getUserInfo()
}

// 关闭修改信息并刷新
const closeAndRefresh = () => {
  changeVisible.value = false
  getUserInfo()
}

// 头像
const circleUrl = ref()

// 修改头像对话框
const avatarVisible = ref(false)

// 修改头像对话框临时变量
const tempAvatar = ref(circleUrl.value)

// 文件记录
const file = ref()

// 刷新头像
const updateAvatar = async () => {
  if (userStore.getAccessToken() !== '') {
    const res = await getAvatar()
    if (res) {
      tempAvatar.value = circleUrl.value = res
      return
    }
  }
  const gender = userInfo.value?.gender
  circleUrl.value = new URL(
    gender ? '../../assets/boy.png' : '../../assets/girl.png',
    import.meta.url,
  ).href
}

// 上传头像前的判断
const beforeAvatarUpload = (file) => {
  // 判断格式
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
  // 是否小于2M
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG) {
    ElNotification({
      title: '提示',
      message: '上传头像图片只能是 JPG、PNG 格式!',
      type: 'warning',
    })
    //将上传的文件换回原来的文件
    tempAvatar.value = circleUrl.value
    return false
  }
  if (!isLt2M) {
    ElNotification({
      title: '提示',
      message: '上传头像图片大小不能超过2MB',
      type: 'warning',
    })
    tempAvatar.value = circleUrl.value
    return false
  }
  //图片符合条件
  return true
}

// 上传头像成功后的操作
const handleAvatarSuccess = (response) => {
  tempAvatar.value = URL.createObjectURL(response.raw)
  file.value = response.raw
}

// 更新新头像
const updateNewAvatar = async () => {
  avatarVisible.value = false
  tempAvatar.value = circleUrl.value
  // 表单数据
  const formData = new FormData()
  formData.append('avatar', file.value)

  startLoading()
  //更新头像
  const res = (await updateAvatarURL(formData)).data
  stopLoading()
  //更新失败
  if (!res.success) {
    ElNotification({
      title: '错误',
      message: '修改头像失败',
      type: 'error',
    })
    return
  }
  //使头像修改框和展示头像的url都变成最新的
  tempAvatar.value = circleUrl.value = await getAvatar()
  //调用父组件的方法
  layoutRef.value.changeAvatarUrl(tempAvatar.value)
}

// 点击头像放大
const onBig = () => {
  ElMessageBox.alert(
    `<img src="${circleUrl.value}" style="max-width: 100%; height: auto; display: block; margin: 0 auto;" />`,
    '预览',
    {
      dangerouslyUseHTMLString: true,
      draggable: true,
      confirmButtonText: '关闭',
    },
  )
}

// 退出登录
const unLogin = () => {
  userStore.removeAccessToken()
  userStore.removeRefreshToken()
  userStore.removeUser()
  router.replace('/login')
}

console.log('user');


getUserInfo()

</script>

<style scoped less="scss">
.user {
  border-top: 1px solid transparent;

  .header {
    display: flex;
    flex-direction: column;

    height: 500px;
    margin: 70px 50px 10px 50px;
    background-color: white;
    border-radius: 5px;

    /* 头像和用户名 */

    .first {
      .avatar-and-main-info {
        display: flex;
        align-items: center;
        gap: 10px;

        min-width: 140px;
        margin: -7px 0 0 10px;

        .el-avatar {
          width: 60px;
          height: 60px;
          cursor: pointer;
          border-radius: 30px;
        }

        .name-and-des {
          position: relative;

          /* 用户名 */

          .name {
            font-size: 1.5rem;
          }

          /* 个人简介 */

          .des {
            position: absolute;
            top: 30px;
            left: 0;
            min-width: 800px;
            font-size: 12px;
            color: #909399;
          }
        }
      }
    }

    /* 基本信息盒子 */

    .second-header {
      margin: 20px 50px 10px 20px;

      .el-descriptions__table {
        background-color: #f5faf6;
      }

      .integral {
        margin-left: 10px;
      }
    }

    .flex-box {
      display: flex;
      justify-content: space-between;
      align-items: center;

      width: 95%;
    }
  }

  .main {
    display: flex;
    flex-direction: column;

    height: 450px;
    margin: 20px 50px 10px 50px;
    background-color: #f5faf6;
    /* 防止子元素margin越级 */
    border-top: 1px solid transparent;

    .title {
      display: block;
      font-size: 1.3rem;
      margin: 14px 0 5px 10px;
      letter-spacing: 1px;
    }

    .el-menu--horizontal {
      --el-menu-horizontal-height: 50px;
    }
  }

  .change-avatar {
    .avatar-uploader {
      display: flex;
      justify-content: center;
      align-items: center;

      .avatar {
        width: 178px;
        height: 178px;
        display: block;
        border-radius: 100px;
      }

      .el-upload {
        border: 1px dashed var(--el-border-color);
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
        transition: var(--el-transition-duration-fast);
      }

      .el-upload:hover {
        border-color: var(--el-color-primary);
      }

      .el-icon.avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 178px;
        height: 178px;
        text-align: center;
      }
    }
  }

  .verification-code {
    position: relative;
    left: 80%;
    bottom: 50%;
  }
}
</style>
